package com.app.conrtoller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.app.dao.mysql.UploadParameterMapper;
import com.app.dao.mysql.YjDataMapper;

import com.app.domain.*;
import com.app.domain.UploadParameter;

import com.app.service.*;
import com.app.utils.MathUtil;
import com.app.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/yj")
public class YjController {

    @Autowired
    YjDataService yjDataService;
    @Autowired
    UploadParameterService uploadParameterService;
    @Autowired
    UploadParameterMapper uploadParameterMapper;
    @Autowired
    YjDataMapper yjDataMapper;
    @Autowired
    UploadService uploadService;
    @Autowired
    SendMessageService sendMessageService;

    @PostMapping("/upload")
    @ResponseBody
    public UploadJsonResult upload(@RequestBody YjUploadData yjUploadData) {
        log.info("upload:" + yjUploadData);
        YjData yjData = new YjData();
        yjData.setDevice_code(yjUploadData.getShebeino());
        yjData.setBridge_code(yjUploadData.getLianghao());
        yjData.setDuct_code(yjUploadData.getKongdaono());
        YjData byDeviceCode = yjDataMapper.findByDeviceCode(yjData);
        if (byDeviceCode == null) {
            //格式化
            try {
                YjUploadData yjUploadData1 = formatYjUploadData(yjUploadData);
                //保存
                yjDataMapper.save1(yjUploadData1);
            } catch (Exception e) {
                log.error(yjUploadData.getShebeino() + "---" + yjUploadData.getLianghao() + ":" + e);
                return UploadJsonResult.error(yjUploadData.getLianghao());
            }
            log.info(yjUploadData.getShebeino() + "---" + yjUploadData.getLianghao() + "---" + yjUploadData.getKongdaono() + "保存成功");
            return UploadJsonResult.ok(yjUploadData.getLianghao());
        } else {
            log.info(yjUploadData.getShebeino() + "---" + yjUploadData.getLianghao() + "---" + yjUploadData.getKongdaono() + "已存在");
            return UploadJsonResult.error(yjUploadData.getLianghao());
        }

    }

    @RequestMapping("/findAll")
    @ResponseBody
    public JsonResult findAll(String bridgeCode, String device_code, String state, @RequestParam(name = "page", required = true, defaultValue = "1") Integer page, @RequestParam(name = "limit", required = true, defaultValue = "10") Integer limit) {
        return yjDataService.selectList(bridgeCode, device_code, state, page, limit);
    }

    @RequestMapping("/update")
    @ResponseBody
    public String update(@RequestParam("id") String id, @RequestParam("field") String field, @RequestParam("value") String value) {
        return yjDataService.ConditionUpdate(id, field, value);
    }

    @RequestMapping("/add")
    @ResponseBody
    public String add(@RequestParam("deviceCode") String deviceCode, @RequestParam("bridgeCode") String bridgeCode, @RequestParam("mudjackDate") String mudjackDate) {

        return yjDataService.save(deviceCode, bridgeCode, mudjackDate);
    }


    @RequestMapping("/updateParameter")
    @ResponseBody
    public String updateParameter(UploadParameter uploadParameter) {
        String update = uploadParameterService.update(uploadParameter);
        return update;
    }

    @RequestMapping("/showParameter")
    @ResponseBody
    public UploadParameter showParameter(String id) {
        UploadParameter one = uploadParameterService.findOne(id);
        return one;
    }

    @RequestMapping("/export")
    public void exportExcelCommon(HttpServletResponse response, @RequestParam(value = "ids[]") String[] ids) throws IOException {
        OutputStream outputStream = null;

        try {
            YjData one = yjDataService.findOne(ids[0]);
            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(one.getBridge_code() + "预应力砼构件压浆施工原始记录表", "UTF-8") + ".xlsx");
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            if (one.getDevice_code().equals("2021070201") || one.getDevice_code().equals("2021103002")) {
//                response.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(one.getBridge_code() + "预应力砼构件压浆施工原始记录表", "UTF-8") + ".xlsx");
                TemplateExportParams params;
                params = new TemplateExportParams(
                        "export/template/lhTemplate.xlsx");
                Map<String, Object> map = uploadService.getExcelData(ids[0], one.getDevice_code());
                outputStream = response.getOutputStream();
                Workbook workbook = ExcelExportUtil.exportExcel(params, map);

                workbook.write(outputStream);
            }
            if (one.getDevice_code().equals("2021071601") || one.getDevice_code().equals("2021082701")) {
//                response.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(one.getBridge_code() + "预应力砼构件压浆施工原始记录表", "UTF-8") + ".xls");
                TemplateExportParams params;
                params = new TemplateExportParams(
                        "export/template/jwTemplate.xlsx");
                Map<String, Object> map = uploadService.getExcelData(ids[0], one.getDevice_code());
                Workbook workbook = ExcelExportUtil.exportExcel(params, map);
                outputStream = response.getOutputStream();
                workbook.write(outputStream);
            }
            if (one.getDevice_code().equals("2022080101")) {
                TemplateExportParams params;
                params = new TemplateExportParams(
                        "export/template/scTemplate.xlsx");
                log.info("进入2022080101");
                Map<String, Object> map = uploadService.getScExcelData(ids[0]);
                log.info("进入2022080102");
                Workbook workbook = ExcelExportUtil.exportExcel(params, map);
                log.info("进入2022080103");
                outputStream = response.getOutputStream();
                log.info("进入2022080104");
                workbook.write(outputStream);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            outputStream.flush();
            outputStream.close();
        }
    }

    @ResponseBody
    @RequestMapping("/graph")
    public Map<String, List> getGraph(String id) {
        Map<String, List> map = yjDataService.getGraphData(id);
        return map;
    }

    private YjUploadData formatYjUploadData(YjUploadData yjUploadData) {
        YjUploadData yjUploadData1 = new YjUploadData();
//                if (StringUtils.isNotEmpty(yjUploadData.getJjyali()))
        yjUploadData1.setShebeino(yjUploadData.getShebeino());
        yjUploadData1.setLianghao(yjUploadData.getLianghao());
        yjUploadData1.setKongdaono(yjUploadData.getKongdaono());
        yjUploadData1.setBaoyalong(yjUploadData.getBaoyalong());
        yjUploadData1.setMudjackDate(yjUploadData.getStartime().split(" ")[0]);
        yjUploadData1.setStartime(yjUploadData.getStartime().split(" ")[1]);
        yjUploadData1.setStoptime(yjUploadData.getStoptime().split(" ")[1]);
        yjUploadData1.setJjyali(formatDouble(yjUploadData.getJjyali()));
        yjUploadData1.setCjyali(formatDouble(yjUploadData.getCjyali()));
        yjUploadData1.setWyyali(formatDouble(yjUploadData.getWyyali()));
        yjUploadData1.setShuijiaobi(formatDouble(yjUploadData.getShuijiaobi()));
        yjUploadData1.setLilunjiangliang(formatDouble(yjUploadData.getLilunjiangliang()));
        yjUploadData1.setJinjiangliang(formatDouble(yjUploadData.getJinjiangliang()));
        yjUploadData1.setChujiangliang(formatDouble(yjUploadData.getChujiangliang()));
        yjUploadData1.setZhenkongyali(formatDouble(yjUploadData.getZhenkongyali()));

        List<Double> jinjiangquxian = new ArrayList<>();
        List<Double> chujiangquxian = new ArrayList<>();
        for (Double aDouble : yjUploadData.getJinjiangquxian()) {
            jinjiangquxian.add(formatDouble(aDouble));
        }
        yjUploadData1.setJinjiangquxian(jinjiangquxian);
        for (Double aDouble : yjUploadData.getChujiangquxian()) {
            chujiangquxian.add(formatDouble(aDouble));
        }
        yjUploadData1.setChujiangquxian(chujiangquxian);
        yjUploadData1.setState("2");
        return yjUploadData1;
    }

    private double formatDouble(double d) {
        DecimalFormat df = new DecimalFormat("#.00");
        d = d / 100;
        return Double.valueOf(df.format(d));
    }

    private String formatDoubletoString(double d) {
        DecimalFormat df = new DecimalFormat("#.00");
        d = d / 100;
        return df.format(d);
    }

}
